  <th:block layout:fragment="scripts">
        <script>
            let contracts = []; // 存储合同数据
            let clients = []; // 存储客户列表
            let opportunities = []; // 存储销售机会列表
            
            document.addEventListener('DOMContentLoaded', function() {
                loadContracts();
                loadClients();
                loadOpportunities();
                
                // 设置表单提交事件
                document.getElementById('contractForm').addEventListener('submit', function(e) {
                    e.preventDefault();
                    saveContract();
                });
                
                // 设置搜索和筛选事件
                document.getElementById('searchContract').addEventListener('input', filterContracts);
                document.getElementById('filterStatus').addEventListener('change', filterContracts);
            });
            
            // 从服务器加载合同列表
            function loadContracts() {
                fetch('/api/sales/contracts/list')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            contracts = result.data;
                            renderContracts();
                        } else {
                            console.error('加载合同列表失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载合同列表失败:', error));
            }
            
            // 加载客户列表用于表单选择
            function loadClients() {
                fetch('/api/sales/clients/list')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            clients = result.data;
                            
                            // 填充客户下拉框
                            const clientSelect = document.getElementById('clientId');
                            clientSelect.innerHTML = '<option value="">请选择客户</option>';
                            
                            clients.forEach(client => {
                                const option = document.createElement('option');
                                option.value = client.id;
                                option.textContent = client.name;
                                clientSelect.appendChild(option);
                            });
                        } else {
                            console.error('加载客户列表失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载客户列表失败:', error));
            }
            
            // 加载销售机会列表用于表单选择
            function loadOpportunities() {
                fetch('/api/sales/opportunities/list')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            opportunities = result.data;
                            
                            // 填充销售机会下拉框
                            const opportunitySelect = document.getElementById('opportunityId');
                            opportunitySelect.innerHTML = '<option value="">请选择关联销售机会</option>';
                            
                            opportunities.forEach(opportunity => {
                                const option = document.createElement('option');
                                option.value = opportunity.id;
                                option.textContent = opportunity.name;
                                opportunitySelect.appendChild(option);
                            });
                        } else {
                            console.error('加载销售机会列表失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载销售机会列表失败:', error));
            }
            
            // 渲染合同列表
            function renderContracts() {
                const table = document.getElementById('contracts-table');
                const tbody = table.querySelector('tbody');
                tbody.innerHTML = '';
                
                if (contracts.length === 0) {
                    const emptyRow = document.createElement('tr');
                    emptyRow.innerHTML = '<td colspan="8" class="text-center">没有找到合同数据</td>';
                    tbody.appendChild(emptyRow);
                    return;
                }
                
                contracts.forEach(contract => {
                    const row = document.createElement('tr');
                    
                    // 设置状态样式
                    let statusClass = '';
                    switch(contract.status) {
                        case 'DRAFT': statusClass = 'badge-secondary'; break;
                        case 'REVIEW': statusClass = 'badge-info'; break;
                        case 'APPROVED': statusClass = 'badge-primary'; break;
                        case 'SIGNED': statusClass = 'badge-success'; break;
                        case 'EXPIRED': statusClass = 'badge-danger'; break;
                        case 'TERMINATED': statusClass = 'badge-dark'; break;
                    }
                    
                    // 获取状态对应的显示文本
                    const statusText = {
                        'DRAFT': '草稿',
                        'REVIEW': '审核中',
                        'APPROVED': '已批准',
                        'SIGNED': '已签署',
                        'EXPIRED': '已过期',
                        'TERMINATED': '已终止'
                    }[contract.status] || contract.status;
                    
                    row.innerHTML = `
                        <td>${contract.id}</td>
                        <td>${contract.contractNumber || '-'}</td>
                        <td>${contract.name}</td>
                        <td>${contract.clientName || '-'}</td>
                        <td>${contract.amount.toLocaleString('zh-CN', {style: 'currency', currency: 'CNY'})}</td>
                        <td>${contract.signingDate || '-'}</td>
                        <td><span class="badge ${statusClass}">${statusText}</span></td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="viewContract(${contract.id})">查看</button>
                            <button class="btn btn-sm btn-primary" onclick="editContract(${contract.id})">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteContract(${contract.id})">删除</button>
                        </td>
                    `;
                    
                    tbody.appendChild(row);
                });
            }
            
            function showAddContractModal() {
                document.getElementById('modalTitle').textContent = '添加合同';
                document.getElementById('contractForm').reset();
                
                // 移除可能存在的ID
                document.getElementById('contractForm').removeAttribute('data-id');
                
                // 当前日期作为默认值
                const today = new Date().toISOString().split('T')[0];
                document.getElementById('signingDate').value = today;
                
                // 显示模态框
                document.getElementById('contractModal').style.display = 'block';
            }
            
            function closeModal() {
                document.getElementById('contractModal').style.display = 'none';
            }
            
            function editContract(contractId) {
                document.getElementById('modalTitle').textContent = '编辑合同';
                
                // 获取合同详情
                fetch(`/api/sales/contracts/${contractId}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const contract = result.data;
                            
                            // 填充表单
                            document.getElementById('contractNumber').value = contract.contractNumber || '';
                            document.getElementById('contractName').value = contract.name;
                            document.getElementById('clientId').value = contract.clientId || '';
                            document.getElementById('opportunityId').value = contract.opportunityId || '';
                            document.getElementById('amount').value = contract.amount;
                            document.getElementById('signingDate').value = contract.signingDate || '';
                            document.getElementById('startDate').value = contract.startDate || '';
                            document.getElementById('endDate').value = contract.endDate || '';
                            document.getElementById('status').value = contract.status;
                            document.getElementById('description').value = contract.description || '';
                            
                            // 设置表单ID用于保存
                            document.getElementById('contractForm').setAttribute('data-id', contract.id);
                            
                            // 显示模态框
                            document.getElementById('contractModal').style.display = 'block';
                        } else {
                            console.error('加载合同详情失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载合同详情失败:', error));
            }
            
            function viewContract(contractId) {
                // 跳转到合同详情页面
                window.location.href = `/sales/contracts/${contractId}`;
            }
            
            function deleteContract(contractId) {
                if (confirm('确定要删除这个合同吗？')) {
                    fetch(`/api/sales/contracts/delete/${contractId}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            // 刷新合同列表
                            loadContracts();
                        } else {
                            alert('删除合同失败: ' + result.message);
                        }
                    })
                    .catch(error => {
                        console.error('删除合同失败:', error);
                        alert('系统错误，请稍后重试');
                    });
                }
            }
            
            function saveContract() {
                const form = document.getElementById('contractForm');
                const contractId = form.getAttribute('data-id');
                const isEdit = !!contractId;
                
                // 表单验证
                if (!form.checkValidity()) {
                    form.reportValidity();
                    return;
                }
                
                const contractData = {
                    contractNumber: document.getElementById('contractNumber').value,
                    name: document.getElementById('contractName').value,
                    clientId: document.getElementById('clientId').value || null,
                    opportunityId: document.getElementById('opportunityId').value || null,
                    amount: parseFloat(document.getElementById('amount').value),
                    signingDate: document.getElementById('signingDate').value || null,
                    startDate: document.getElementById('startDate').value || null,
                    endDate: document.getElementById('endDate').value || null,
                    status: document.getElementById('status').value,
                    description: document.getElementById('description').value
                };
                
                if (isEdit) {
                    contractData.id = parseInt(contractId);
                }
                
                const url = isEdit ? '/api/sales/contracts/update' : '/api/sales/contracts/add';
                const method = isEdit ? 'PUT' : 'POST';
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(contractData)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        // 关闭模态框，重新加载合同列表
                        closeModal();
                        loadContracts();
                    } else {
                        alert('保存合同失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('保存合同失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
            
            function filterContracts() {
                const searchTerm = document.getElementById('searchContract').value.toLowerCase();
                const statusFilter = document.getElementById('filterStatus').value;
                
                // 构建过滤条件
                const params = new URLSearchParams();
                if (searchTerm) params.append('search', searchTerm);
                if (statusFilter) params.append('status', statusFilter);
                
                // 发送带参数的请求
                fetch(`/api/sales/contracts/list?${params.toString()}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            contracts = result.data;
                            renderContracts();
                        } else {
                            console.error('筛选合同失败:', result.message);
                        }
                    })
                    .catch(error => console.error('筛选合同失败:', error));
            }
            
            function resetFilters() {
                document.getElementById('searchContract').value = '';
                document.getElementById('filterStatus').value = '';
                loadContracts(); // 重新加载所有合同
            }
            
            // 选择客户时的联动处理
            document.getElementById('clientId').addEventListener('change', function() {
                const selectedClientId = this.value;
                if (selectedClientId) {
                    // 可以在这里加载该客户关联的销售机会
                    loadClientOpportunities(selectedClientId);
                }
            });
            
            // 加载指定客户的销售机会
            function loadClientOpportunities(clientId) {
                fetch(`/api/sales/opportunities/list?clientId=${clientId}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const clientOpportunities = result.data;
                            
                            // 更新销售机会下拉框
                            const opportunitySelect = document.getElementById('opportunityId');
                            opportunitySelect.innerHTML = '<option value="">请选择关联销售机会</option>';
                            
                            clientOpportunities.forEach(opportunity => {
                                const option = document.createElement('option');
                                option.value = opportunity.id;
                                option.textContent = opportunity.name;
                                opportunitySelect.appendChild(option);
                            });
                        } else {
                            console.error('加载客户销售机会失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载客户销售机会失败:', error));
            }
            
            // 选择销售机会时自动填充金额
            document.getElementById('opportunityId').addEventListener('change', function() {
                const selectedOpportunityId = this.value;
                if (selectedOpportunityId) {
                    const selectedOpportunity = opportunities.find(opp => opp.id == selectedOpportunityId);
                    if (selectedOpportunity) {
                        // 自动填充金额
                        document.getElementById('amount').value = selectedOpportunity.amount;
                    }
                }
            });
            
            // 日期验证 - 确保结束日期不早于开始日期
            document.getElementById('endDate').addEventListener('change', function() {
                const startDate = document.getElementById('startDate').value;
                const endDate = this.value;
                
                if (startDate && endDate && new Date(endDate) < new Date(startDate)) {
                    alert('结束日期不能早于开始日期');
                    this.value = '';
                }
            });
            
            // 上传合同文件
            function uploadContractFile(contractId) {
                const fileInput = document.createElement('input');
                fileInput.type = 'file';
                fileInput.accept = '.pdf,.doc,.docx';
                
                fileInput.addEventListener('change', function() {
                    if (this.files.length === 0) return;
                    
                    const file = this.files[0];
                    const formData = new FormData();
                    formData.append('file', file);
                    formData.append('contractId', contractId);
                    
                    fetch('/api/sales/contracts/upload', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            alert('文件上传成功');
                            loadContracts(); // 刷新列表
                        } else {
                            alert('文件上传失败: ' + result.message);
                        }
                    })
                    .catch(error => {
                        console.error('文件上传失败:', error);
                        alert('系统错误，请稍后重试');
                    });
                });
                
                fileInput.click();
            }
            
            // 自动生成合同编号
            function generateContractNumber() {
                const prefix = 'CT';
                const date = new Date();
                const year = date.getFullYear().toString().substr(-2);
                const month = ('0' + (date.getMonth() + 1)).slice(-2);
                const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
                
                const contractNumber = `${prefix}${year}${month}-${random}`;
                document.getElementById('contractNumber').value = contractNumber;
            }
        </script>
    </th:block> 